<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size">
        <el-row>
          <el-form-item>
            <el-input v-model="filters.number" placeholder="优惠券编号" style="width: 200px;"></el-input>
          </el-form-item>

          <el-form-item>
            <el-select
              v-model="filters.shop_id"
              style="width: 200px;"
              filterable
              placeholder="所属店铺"
            >
              <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-input
              v-model="filters.equivalencyMin"
              type="number"
              placeholder="最低等价金额"
              style="width: 200px;"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-input
              v-model="filters.equivalencyMax"
              type="number"
              placeholder="最高等价金额"
              style="width: 200px;"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-input
              v-model="filters.fullMin"
              type="number"
              placeholder="最低金额满减"
              style="width: 200px;"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-input
              v-model="filters.fullMax"
              type="number"
              placeholder="最高金额满减"
              style="width: 200px;"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-input
              v-model="filters.numsMin"
              type="number"
              placeholder="最低数量满减"
              style="width: 200px;"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-input
              v-model="filters.numsMax"
              type="number"
              placeholder="最高数量满减"
              style="width: 200px;"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-date-picker
              v-model="filters.createMin"
              type="date"
              placeholder="创建时间始"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              style="width: 200px;"
            ></el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-date-picker
              v-model="filters.createMax"
              type="date"
              placeholder="创建时间末"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              style="width: 200px;"
            ></el-date-picker>
          </el-form-item>

          <el-row>
            <el-form-item>
              <kt-button label="新增优惠券配置" type="primary" @click="handleAdd" />
            </el-form-item>
            <el-form-item>
              <kt-button label="启用" type="primary" @click="startRule" />
            </el-form-item>
            <el-form-item>
              <kt-button label="停用" type="primary" @click="endRule" />
            </el-form-item>
            <el-form-item>
              <kt-button label="关联活动商品" type="primary" @click="relatedProducts" />
            </el-form-item>

            <div style="float:right">
              <el-form-item>
                <kt-button
                  icon="fa fa-search"
                  :label="$t('action.search')"
                  type="primary"
                  @click="findPage(null)"
                />
              </el-form-item>
              <el-form-item>
                <kt-button
                  icon="fa fa-refresh" :label="$t('action.reset')"
                  type="primary"
                  @click="resetForm('filters')"
                />
              </el-form-item>
            </div>
          </el-row>
        </el-row>
      </el-form>
    </div>
    <div class="toolbar" style="float:right;padding-top:10px;padding-right:15px;">
      <el-form :inline="true" :size="size">
        <el-form-item>
          <el-button-group>
            <el-tooltip content="刷新" placement="top">
              <el-button icon="fa fa-refresh" @click="findPage(null)"></el-button>
            </el-tooltip>
            <el-tooltip content="列显示" placement="top">
              <el-button icon="fa fa-filter" @click="displayFilterColumnsDialog"></el-button>
            </el-tooltip>
            <el-tooltip content="导出" placement="top">
              <el-button icon="fa fa-file-excel-o" @click="downloadExcel" id="downloadExcel"></el-button>
            </el-tooltip>
          </el-button-group>
        </el-form-item>
      </el-form>
      <!--表格显示列界面-->
      <table-column-filter-dialog
        ref="tableColumnFilterDialog"
        :columns="columns"
        @handleFilterColumns="handleFilterColumns"
      ></table-column-filter-dialog>
    </div>
    <!--表格内容栏-->
    <cy-table
      :height="350"
      ref="CyTable"
      :data="pageResult"
      :columns="filterColumns"
      @selectionChange="selectionChange"
      @findPage="findPage"
      @handleEdit="handleEdit"
      @handleDelete="handleDelete"
    ></cy-table>
    <!--新增编辑界面-->
    <el-dialog
      :title="operation?'新增':'编辑'"
      width="40%"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dataForm"
        label-width="80px"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size"
        label-position="right"
      >
        <el-form-item label="所属商铺" prop="shop_id">
          <el-select v-model="dataForm.shop_id" placeholder="所属店铺" style="width: 100%;">
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="等价金额" prop="money">
          <el-input type="number" v-model="dataForm.money" auto-complete="off" @input="watchMoney"></el-input>
        </el-form-item>
        <el-form-item label="需要达到的订单金额" prop="full_money">
          <el-input type="number" v-model="dataForm.full_money" auto-complete="off" @input="watchFullMoney"></el-input>
        </el-form-item>
        <el-form-item label="需要达到的订单数量" prop="full_nums">
          <el-input type="number" v-model="dataForm.full_nums" auto-complete="off" @input="watchNums"></el-input>
        </el-form-item>

        <el-form-item label="有效开始时间" prop="start">
          <el-date-picker
            v-model="dataForm.starttime"
            style="width:100%"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            v-on:input = "watchStart"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="有效结束时间" prop="end">
          <el-date-picker
            v-model="dataForm.endtime"
            style="width:100%"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            v-on:input="watchEnd"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :size="size" @click.native="dialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="submitForm"
          :loading="false"
        >{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>


      <el-dialog title="指定商品页面" :visible.sync="checkpages" width="30%"  height="100%">
      <el-form style="text-align:center">
        <el-row>
          <el-form-item>
            <span>选择范围:</span>
            <el-select v-model="the_products" placeholder="请选择">
              <el-option label="全平台" :value="0"></el-option>
              <el-option label="本商铺通用" :value="1"></el-option>
              <el-option label="指定商品" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:right">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="checkpaged">确 定</el-button>
      </div>
    </el-dialog>


     
  </div>
</template>

<script>
import PopupTreeInput from "@/components/PopupTreeInput";
import CyTable from "@/views/Core/CyTable";
import KtButton from "@/views/Core/KtButton";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import { format } from "@/utils/datetime";
import { exportExcel } from "@/utils/excel";
export default {
  components: {
    PopupTreeInput,
    CyTable,
    KtButton,
    TableColumnFilterDialog
  },
  data() {
    return {
      size: "small",
      filters: {
        number: "",
        shop_id: "",
        equivalencyMin: "",
        equivalencyMax: "",
        fullMin: "",
        fullMax: "",
        numsMin: "",
        numsMax: "",
        createMin: "",
        createMax: "",
      },
      the_products:"",
      columns: [],
      filterColumns: [],
      pageRequest: { pageNum: 1, pageSize: 10 },
      pageResult: {},
      options: {},
      checkpages:false,
      operation: false, // true:新增, false:编辑
      dialogVisible: false, // 新增编辑界面是否显示
      editLoading: false,
      dataFormRules: {
        shop_id: [{ required: true, message: "请选择商铺", trigger: "blur" }],
        money: [
          { required: true, message: "请输入等价金额", trigger: "blur" }
        ],
        full_money: [{ required: true, message: "请输入订单金额", trigger: "blur" }],
        full_nums: [{ required: true, message: "请输入订单数量", trigger: "blur" }],
        starttime: [{ required: true, message: "请输入有效开始时间", trigger: "blur" }],
        endtime: [{ required: true, message: "请输入有效结束时间", trigger: "blur" }]
       
      },

      // 新增编辑界面数据
      dataForm: {
        shop_id: "",
        money: "",
        full_money: "",
        full_nums: "",
        starttime: "",
        endtime: " "
      },
      selections: []
    };
  },
  methods: {

    //监听金额数量
    watchMoney(){
      let this_ = this;
      if(this_.dataForm.money<0){
         this.$message({ message: "等价金额不能为负 ", type: "error"});
         this_.dataForm.money = ""
      }
    },
    watchFullMoney(){
         let this_ = this ; 
         if(this_.dataForm.full_money<0){
           this.$message({message :"订单金额不能为负",type:"error"});
           this_.dataForm.full_money = "" 
           return
         }
    },
     watchNums(){
         let this_ = this ; 
         if(this_.dataForm.full_nums<0){
           this.$message({message :"订单数量不能为负",type:"error"});
           this_.dataForm.full_nums = "" 
           return
         }
    },
    //动态监听日期
     watchStart(){
       var this_ = this;
      let starttime =this_.dataForm.starttime;
      let endtime = this_.dataForm.endtime;
        if(new Date(starttime).getTime()>=new Date(endtime).getTime()){
          this.$message({ message: "开始日期不能晚于结束日期 ", type: "error"});
          this_.dataForm.starttime = ""
          return false;
        }
     },

    watchEnd(){
      
      var this_ = this;
      let starttime =this_.dataForm.starttime;
      let endtime = this_.dataForm.endtime;
        if(new Date(endtime).getTime()<=new Date(starttime).getTime()){
          this.$message({ message: "结束日期不能早于开始日期 ", type: "error"});
           this_.dataForm.endtime = ""
          return false;
        }
    },
    selectionChange: function(data) {
      this.selections = data.selections;
    },
    // 获取分页数据
    findPage: function(data) {
      this.filters.t = "marketCoupons";
      this.$refs.CyTable.findPage(this.filters);
    },

    // 批量删除
    handleDelete: function(data) {
      var ids = "";
      for (var i = 0; i < data.params.length; i++) {
        ids = ids + data.params[i].id + ",";
      }
      data.params.t = "marketCoupons";
      data.params.ids = ids;
      this.utils.request.deleteUserInfo(data.params, data.callback);
    },

    // 显示新增界面
    handleAdd: function() {
      this.dialogVisible = true;
      this.operation = true;
      this.dataForm = {};
      console.log(dataForm);
    },
    //列表下载
    downloadExcel() {
      this.$confirm("确定下载列表文件?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let filename = "优惠卷配置";
          this.$refs.CyTable.exportData(
            this.filters,
            this.filterColumns,
            filename
          );
        })
        .catch(() => {});
    },
    // 显示编辑界面
    handleEdit: function(params) {
      console.log(params);
      this.dialogVisible = true;
      this.operation = false;
      this.dataForm = Object.assign({}, params.row);
    },

   // 编辑
    submitForm: function() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
            
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            let params = Object.assign({}, this.dataForm);
            params.t = "marketCoupons";
            this.utils.request.saveMarketCoupon(params, this.saveSeckillBack);
          });
        }
      });
    },

    // 新增修改回调
    saveSeckillBack: function(data) {
      if (data.code == "0000") {
        this.$message({ message: "操作成功", type: "success" });
        this.dialogVisible = false;
        this.$refs["dataForm"].resetFields();
      } else {
        this.$message({ message: "操作失败, " + data.msg, type: "error" });
      }
      this.findPage({ t: "marketCoupons" });
      this.dialogVisible = false;
      this.operation = false;
      this.editLoading = false;
    },
    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },
    // 处理表格列过滤显示
    displayFilterColumnsDialog: function() {
      this.$refs.tableColumnFilterDialog.setDialogVisible(true);
    },
    // 处理表格列过滤显示
    handleFilterColumns: function(data) {
      this.filterColumns = data.filterColumns;
      this.$refs.tableColumnFilterDialog.setDialogVisible(false);
    },
    // 处理表格列过滤显示
    initColumns: function() {
      this.columns = [
        { prop: "id", label: "ID", minWidth: 50 },
        { prop: "number", label: "优惠券编号", minWidth: 120 },
        { prop: "shopname", label: "所属商铺", minWidth: 120 },
        { prop: "money", label: "等价金额", minWidth: 120 },
        { prop: "full_money", label: "金额满减", minWidth: 120 },
        { prop: "full_nums", label: "商品数量", minWidth: 120 },
        { prop: "theProducts", label: "使用范围", minWidth: 120 },
        { prop: "starttime", label: "有效开始时间", minWidth: 120 },
         { prop: "endtime", label: "有效结束时间", minWidth: 120 },
          { prop: "statusval", label: "状态", minWidth: 120 },
        { prop: "create_time", label: "创建时间", minWidth: 120 },
        { prop: "creatorname", label: "创建人", minWidth: 120 },
        { prop: "update_time", label: "修改时间", minWidth: 120 },
        { prop: "updatorname", label: "修改人", minWidth: 120 }
      ];
      var temp = [];
      $.each(this.columns, function(key, val) {
        temp.push(val);
      });
      this.filterColumns = temp;
    },
    resetForm(formName) {
      this.filters = {
        name: "",
        code: "",
        types: "",
        sortno: ""
      };
      this.findPage({ t: "marketCoupons" });
    },
    // 所属商品分类
    queryProType() {
      var that = this;
      this.utils.request.queryUserList({ t: "shop" }, function(data) {
        that.options = data.data;
      });
    },
    //启用停用按钮
    //启用
    startRule: function() {
      if (this.selections.length != 1) {
        this.$message({ message: "请选择一条数据", type: "error" });
        return;
      } else {
        var data = {};
        data.id = data.id = this.selections[0].id;
        data.t = "marketCoupons";
        data.status = 1;

        var this_ = this;
        this.utils.request.editUserInfo(data, function(res) {
          if (res.code == "0000") {
            this_.$message({ message: "启用成功", type: "success" });
            
            this_.findPage();
          } else {
            this_.$message({ message: res.msg, type: "error" });
          }
        });
      }

     
    },

    //停用按钮
    endRule: function() {
      if (this.selections.length != 1) {
        this.$message({ message: "请选择一条数据", type: "error" });
        return;
      } else {
        var data = {};
        data.id = this.selections[0].id;
        data.t = "marketCoupons";
        data.status = 0;

        var this_ = this;
        this.utils.request.editUserInfo(data, function(res) {
          if (res.code == "0000") {
            this_.$message({ message: "停用成功", type: "success" });
            
            this_.findPage();
          } else {
            this_.$message({ message: res.msg, type: "error" });
          }
        });
      }

     
    },
    //关联按钮
    relatedProducts: function() {
      if (this.selections.length != 1) {
        this.$message({ message: "请选择一条数据", type: "error" });
        this.checkpages = false;
        return;
      } else {
        this.checkpages = true;
      }
    },
     //指定商品
    checkpaged: function() {
       var data = {};
        data.id = this.selections[0].id;
        data.t = "marketCoupons";
        data.the_products = this.the_products;
        var this_ = this;
        if(" "!=this.the_products&&this.the_products==2){
                this.$router.push({ path:'/product/productEntry',query:{couponid: this.selections[0].id}})   
        }else{
        this.utils.request.editUserInfo(data, function(res) {
          if (res.code == "0000") {
            this_.$message({ message: "操作成功", type: "success" });
            this_.checkpages = false;
            this_.findPage();
          } else {
            this_.$message({ message: res.msg, type: "error" });
          }
        });
        }
    },

    //取消按钮
    cancel:function(){
      this.selections[0].id = " ";
       var this_ = this;
       this_.checkpages = false;
        this_.findPage();
    }
    
  },

  mounted() {
    this.initColumns();
    this.queryProType();
  }
};
</script>

<style scoped>
</style>